package com.shhm.admin.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.shhm.admin.mapper.StudentMapper;
import com.shhm.admin.service.StudentService;
import com.shhm.common.dto.request.RequestList;
import com.shhm.common.dto.request.admin.StudentReq;
import com.shhm.common.dto.response.AjaxResultPlus;
import com.shhm.common.dto.response.admin.StudentVO;
import com.shhm.common.entity.admin.StudentEntity;
import com.shhm.admin.mapper.UserMapper;
import com.shhm.common.mapper.UserUniversityMapper;
import com.shhm.common.utils.ResponseUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @author JackZ
 * @version 1.0
 * @description: 学生信息服务实现类
 * @date 2025/9/20
 */
@Service
public class StudentServiceImpl implements StudentService {
    @Resource
    private StudentMapper studentMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserUniversityMapper userUniversityMapper;

    @Override
    public AjaxResultPlus auditPageList(Integer pageNum, Integer pageSize, StudentReq entity) {
        PageDTO<StudentVO> page = new PageDTO<>(pageNum, pageSize);
        PageDTO<StudentVO> result = studentMapper.auditPageList(page, entity);
        return AjaxResultPlus.success(result, false);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResultPlus auditStudent(StudentReq entity, HttpServletRequest request) {
        if (Objects.isNull(entity.getId())) {
            return AjaxResultPlus.error("数据ID不能为空");
        }
        if (Objects.isNull(entity.getDataStatus())) {
            return AjaxResultPlus.error("审核状态不能为空");
        }

        // 检查学生信息是否存在
        StudentEntity student = studentMapper.selectById(entity.getId());
        if (Objects.isNull(student)) {
            return AjaxResultPlus.error("学生信息不存在");
        }

        // 更新审核状态和版本号
        student.setDataStatus(entity.getDataStatus());
        student.setDataVersion(student.getDataVersion() + 1);
        student.setUpdateTime(LocalDateTime.now());
        student.setAuditBy(entity.getAuditBy());

        return ResponseUtil.sqlExeIsSuccess(studentMapper.updateById(student));
    }

    @Override
    public AjaxResultPlus pageList(Integer pageNum, Integer pageSize, StudentReq entity) {
        PageDTO<StudentVO> page = new PageDTO<>(pageNum, pageSize);
        PageDTO<StudentVO> result = studentMapper.pageList(page, entity);
        return AjaxResultPlus.success(result, false);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResultPlus add(StudentReq entity, HttpServletRequest request) {
        if (Objects.isNull(entity.getUserId())) {
            return AjaxResultPlus.error("用户ID不能为空");
        }
        if (Objects.isNull(entity.getStudentId()) || entity.getStudentId().trim().isEmpty()) {
            return AjaxResultPlus.error("学号不能为空");
        }
        if (Objects.isNull(entity.getUniversityCode()) || entity.getUniversityCode().trim().isEmpty()) {
            return AjaxResultPlus.error("高校代码不能为空");
        }

        // 检查用户是否存在
        if (Objects.isNull(userMapper.selectById(entity.getUserId()))) {
            return AjaxResultPlus.error("用户不存在");
        }

        // 检查用户和学号的组合是否已存在
        if (Objects.nonNull(studentMapper.selectByUserIdAndStudentId(entity.getUserId(), entity.getStudentId()))) {
            return AjaxResultPlus.error("该用户已绑定此学号");
        }

        // 创建学生信息
        StudentEntity student = new StudentEntity();
        student.setStudentId(entity.getStudentId());
        student.setUserId(entity.getUserId());
        student.setUniversityCode(entity.getUniversityCode());
        student.setDataStatus(3); // 默认设置为正常状态
        student.setDataVersion(0);
        student.createLocalDateTime();

        return ResponseUtil.sqlExeIsSuccess(studentMapper.insert(student));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResultPlus update(StudentReq entity, HttpServletRequest request) {
        if (Objects.isNull(entity.getId())) {
            return AjaxResultPlus.error("数据ID不能为空");
        }

        // 检查学生信息是否存在
        StudentEntity student = studentMapper.selectById(entity.getId());
        if (Objects.isNull(student)) {
            return AjaxResultPlus.error("学生信息不存在");
        }

        // 检查版本号是否匹配
        if (!Objects.equals(student.getDataVersion(), entity.getDataVersion())) {
            return AjaxResultPlus.error("数据已被其他用户修改，请刷新页面后重试");
        }

        // 更新学生信息
        student.setStudentId(entity.getStudentId());
        student.setUserId(entity.getUserId());
        student.setUniversityCode(entity.getUniversityCode());
        student.setDataStatus(entity.getDataStatus());
        student.setDataVersion(student.getDataVersion() + 1);
        student.setUpdateTime(LocalDateTime.now());

        return ResponseUtil.sqlExeIsSuccess(studentMapper.updateById(student));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResultPlus delete(RequestList ids) {
        List<Object> list = ids.getList();
        if (list == null || list.isEmpty()) {
            return AjaxResultPlus.error("请选择要删除的数据");
        }

        return ResponseUtil.sqlExeIsSuccess(studentMapper.deleteBatchIds(list));
    }
}